package com.powerhua.xsys.workflow.web;

import com.powerhua.core.bean.BeansRegisterLocator;
import com.powerhua.core.utils.EncodingUtil;
import com.powerhua.core.web.IServletAction;
import com.powerhua.workflow.logic.WorkflowManager;
import com.powerhua.workflow.logic.jbpm.WorkflowManagerImpl;
import com.powerhua.xsys.workflow.domain.WorkflowDefinition;
import com.powerhua.xsys.workflow.logic.IWorkflowManager;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 *
 * @author Brian.Xie
 */
public class WorkflowAction implements IServletAction{
    
    

    @Override
    public String doAction(HttpServletRequest request) {
        StringBuffer result = new StringBuffer("");
        // 从session中获取用户信息
        HttpSession session = request.getSession(true);
        String userName = (String)session.getAttribute("user_name");
        //userName = request.getParameter("user");
        String actorId = getUserActorIdByUserName(userName);
        
        String action = request.getParameter("act");
        if("listUserTask".equals(action)) {
            String workflowName = request.getParameter("wf");
            String userTaskStr = listUserTask(actorId, workflowName);
            result.append(userTaskStr);
        } else if("processTask".equals(action)) {
            String taskId = request.getParameter("tid");
            String taskContent = request.getParameter("tc");
            String nextTaskTemp = request.getParameter("nt");
            String nextTask = EncodingUtil.isoToUtf8(nextTaskTemp);
            String processResult = processTask(actorId, taskId, 
                    nextTask, taskContent);
            result.append(processResult);
        } else if("getTaskContent".equals(action)) {
            String taskId = request.getParameter("tid");
            String isStartStr = request.getParameter("start");
            int isStart = 0; // 查看
            if("1".equals(isStartStr)) {
                isStart = 1; // 执行
            }
            String taskContent = getTaskContent(actorId, taskId, isStart);
            result.append(taskContent);
        } else if("createProcess".equals(action)) {
            String workflowName = request.getParameter("wf");
            String taskContent = request.getParameter("tc");
            String taskId = startProcess(actorId, workflowName, taskContent);
            result.append(taskId);
        } else if("listWorkflowDefs".equals(action)) {
            result.append(listWorkflowDefs());
        }
        
        // 返回
        return result.toString();
    }
    
    private String listWorkflowDefs() {
        IWorkflowManager wfm = (IWorkflowManager)BeansRegisterLocator.getBean("workflowManager");
        List list = wfm.getAllWorkflow();
        
        StringBuffer result = new StringBuffer("");
        result.append("[");
        for(int i = 0; i < list.size(); i++){
            WorkflowDefinition def = (WorkflowDefinition)list.get(i);
            result.append("[");
            result.append("'" + def.getDefName() + "',"); // 流程名称
            result.append("'" + def.getDefDesc() + "',"); // 描述
            result.append("'" + def.getDefVersion() + "',"); // 版本
            result.append("'new^javascript:alert(0)',"); // 新流程
            result.append("'start^javascript:alert(1)',"); // 任务
            result.append("'view^javascript:alert(2)'"); // 图例
            result.append("]");
            if(i < list.size() - 1) {
                result.append(",");
            }
        }
        result.append("]");
        return result.toString();
    }
    
    private String listUserTask(String userSwimlane, String workflowName) {
        StringBuffer result = new StringBuffer("");
        WorkflowManager wfm = new WorkflowManagerImpl();
        String tasksStr = wfm.getTasksByUserId(userSwimlane, workflowName, "");
        
        // 
        try {
            Document doc = DocumentHelper.parseText(tasksStr);
            Element root = doc.getRootElement();
            List list = root.elements("task");
            Iterator itr = list.iterator();
            result.append("<rows>");
            while(itr.hasNext()) {
                Element e = (Element)itr.next();
                result.append("<row>");
                result.append("<col>" + e.elementText("task-instance") + "</col>");
                result.append("<col>" + e.elementText("process-definition") + "</col>");
                result.append("<col>" + e.elementText("task-start") + "</col>");
                result.append("<col>execute</col>");
                result.append("<col>view</col>");
                result.append("</row>");
            }
            result.append("</rows>");
        } catch (DocumentException ex) {
            
        }
        
        result.append(tasksStr);
        return result.toString();
    }
    
    private String processTask(String userSwimlane, String taskId, 
            String nextTask, String taskContent) {
        StringBuffer result = new StringBuffer("");
        WorkflowManager wfm = new WorkflowManagerImpl();
        String processResult = wfm.executeTask(userSwimlane, taskId, nextTask, taskContent, null);
        result.append(processResult);
        return result.toString();
    }
    
    private String startProcess(String userSwimlane, String workflowName, String taskContent) {
        StringBuffer result = new StringBuffer("");
        WorkflowManager wfm = new WorkflowManagerImpl();
        String taskId = wfm.newProcess(userSwimlane, workflowName, taskContent, null);
        result.append(taskId);
        return result.toString();
    }
    
    private String getTaskContent(String userSwimlane, String taskId, int isStart) {
        WorkflowManager wfm = new WorkflowManagerImpl();
        String taskContent = wfm.getTaskContentByWorkflowId(userSwimlane, taskId, isStart);
        return taskContent;
    }
    
    private String getUserActorIdByUserName(String userName) {
        return userName;
    }
    
    /*
     * temp
    public String getAllWorkflow() {
        StringBuffer result = new StringBuffer("");
        result.append("<workflow-definitions>");
        
        List list = workflowDao.getAllWorkflowDefs();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            result.append("<workflow-definition>");
            WorkflowDefinition def = (WorkflowDefinition) it.next();
            result.append("<def-id>" + def.getId() + "</def-id>");
            result.append("<def-name>" + def.getDefName() + "</def-name>");
            result.append("<def-desc>" + def.getDefDesc() + "</def-desc>");
            result.append("<form-id>" + def.getFormId() + "</form-id>");
            result.append("<jbpm-def-id>" + def.getDefId() + "</jbpm-def-id>");
            result.append("<jbpm-def-version>" + def.getDefVersion() + "</jbpm-def-version>");
            result.append("<create-date>" + def.getCreateDate() + "</create-date>");
            result.append("<modify-date>" + def.getModifyDate() + "</modify-date>");
            result.append("</workflow-definition>");
        }
        result.append("</workflow-definitions>");
        return result.toString();
    }
    */
}
